<template>
    <div
        class="contract-detial-page insuranceInfoView"
        :class="readOnly ? 'read':'write'"
    >
        <Card>
            <Form class="" ref="insuranceForm" :model="insuranceForm" :rules="insuranceFormValidate"
                  :label-width="150"
                  inline>
                <Affix :offset-top="120">
                    <div style="text-align: left;"
                         v-if="!this.isSP && this.editFlag && this.processStatus!=='draft' && this.processStatus!=='toBeRepaired'">
                        <Button type="primary" @click="cancel">返回</Button>
                        <Button type="primary" v-if="!readOnly" :loading="submitLoading" @click="submitInsurance">保存
                        </Button>
                        <Button type="primary" v-if="!readOnly" @click="through">通过</Button>
                        <Button type="primary" v-if="!readOnly" @click="goBack">退回</Button>
                        <Button type="primary" v-if="!readOnly" @click="refuse">拒绝</Button>
                    </div>
                    <div style="text-align: right;" v-else>
                        <Button type="primary" @click="cancel">返回</Button>
                        <Button type="primary" v-if="!readOnly" :loading="submitLoading" @click="submitInsurance">保存
                        </Button>
                        <Button type="primary" v-if="!readOnly" @click="submit">提交</Button>
                    </div>
                </Affix>
                <Collapse v-model="openPanel">
                    <Panel name="0" v-if="!this.isSP && this.editFlag">
                        <!-- <Alert>日志信息</Alert> -->
                        日志信息
                        <div class="content" slot="content">
                            <!--日志信息-->
                            <approveHistory ref="approveHistory" :Obj="Obj"/>
                        </div>
                    </Panel>
                    <Panel name="1">
                        <!-- <Alert>合同信息</Alert> -->
                        合同信息
                        <div class="content" slot="content">
                            <!--合同信息-->
                            <contractInfo ref="contractInfo" :Obj="Obj"/>
                        </div>
                    </Panel>
                    <Panel name="2">
                        <!-- <Alert>金融产品</Alert> -->
                        金融产品
                        <div class="content" slot="content">
                            <!--金融信息-->
                            <financeInfo ref="financeInfo" :Obj="Obj" type="insurance"/>
                        </div>
                    </Panel>
                    <Panel name="3">
                        <!-- <Alert>资产信息</Alert> -->
                        资产信息
                        <div class="content" slot="content">
                            <!--资产信息-->
                            <custAssetInfo ref="custAssetInfo" :Obj="Obj" type="insurance"/>
                        </div>
                    </Panel>
                    <Panel name="4" v-if="affiliatedType">
                        <!-- <Alert>挂靠信息</Alert> -->
                        挂靠信息
                        <div class="content" slot="content">
                            <!--挂靠信息-->
                            <custAnchorInfo ref="custAnchorInfo" @affType="affType" :Obj="Obj"/>
                        </div>
                    </Panel>
                    <Panel name="5">
                        <!-- <Alert>保险信息</Alert> -->
                        保险信息
                        <div class="content" slot="content">
                            <!--保险信息-->
                            <custInsuranceInfo ref="custInsuranceInfo" :Obj="Obj"/>
                        </div>
                    </Panel>
                    <Panel name="6">
                        <!-- <Alert>业务办理</Alert> -->
                        业务办理
                        <div class="content" slot="content">
                            <!--业务办理-->
                            <insuranceBusiness :readOnly="readOnly"
                                               ref="insuranceBusiness" :Obj="Obj" :isApprove="isApprove"/>
                        </div>
                    </Panel>
                    <Panel name="7">
                        <!-- <Alert>业务办理</Alert> -->
                        邮寄授权书原件
                        <div class="content" slot="content">
                            <Row>
                                <Checkbox :disabled="readOnly" v-model="insuranceForm.isSend"
                                          type="logo-twitter" label="邮寄授权书原件">
                                    <span>邮寄授权书原件</span>
                                </Checkbox>
                            </Row>
                            <Row>
                                <FormItem v-if="insuranceForm.isSend" label="收件人" prop="consignee">
                                    <Input v-model="insuranceForm.consignee" :disabled="readOnly"/>
                                </FormItem>
                                <FormItem v-if="insuranceForm.isSend" label="收件人电话" prop="consigneePhone">
                                    <Input v-model="insuranceForm.consigneePhone"
                                           :disabled="readOnly" maxlength="11"/>
                                </FormItem>
                                <!--                                <FormItem v-if="insuranceForm.isSend" label="收件地址" prop="consigneeAddress">-->
                                <!--                                    <Input v-model="insuranceForm.consigneeAddress" :disabled="readOnly"/>-->
                                <!--                                </FormItem>-->
                                <PlaceCascade
                                    v-if="insuranceForm.isSend"
                                    label="收件地址"
                                    value="consigneeAdd"
                                    detailValue="consigneeAddress"
                                    :form="insuranceForm"
                                    :isDetailAddress="true"
                                    :isDisabled="readOnly"
                                    :location="initLoadData"
                                />
                            </Row>
                            <Row>
                                <FormItem v-if="insuranceForm.isSend && !this.isSP && (isApprove || isApproved)"
                                          label="快递公司"
                                          prop="trackingCompany">
                                    <Select :disabled="readOnly" v-model="insuranceForm.trackingCompany"
                                            style="width:160px"
                                            clearable
                                            placeholder="快递公司">
                                        <Option v-for="item in dataDic.trackingCompany" :value="item.value"
                                                :label="item.title"
                                                :key="item.value">{{ item.title }}
                                        </Option>
                                    </Select>
                                </FormItem>
                                <FormItem v-if="insuranceForm.isSend&& !this.isSP && (isApprove || isApproved)"
                                          label="快递单号"
                                          prop="trackingNo">
                                    <Input :disabled="readOnly" v-model="insuranceForm.trackingNo"/>
                                </FormItem>
                            </Row>
                        </div>
                    </Panel>

                </Collapse>
                <Collapse v-model="openPanel">
                    <Panel name="8"
                           v-if="(!readOnly &&!this.isSP && this.editFlag && this.processStatus!=='draft' && this.processStatus!=='toBeRepaired')||this.processStatus==='approved'">
                        <!-- <Alert>业务办理</Alert> -->
                        审批区域
                        <div class="content" slot="content">
                            <ContractCurrentUser ref="contractCurrentUser" :Obj="Obj" @childUserForm="childUserForm"
                                                 @closeSpin="closeSpin"/>
                        </div>
                    </Panel>
                </Collapse>

            </Form>
            <div>
                <Modal @on-visible-change="cancels" v-model="insuranceBusiness" :title="caseTitle" :width="900"
                       :closable="false" :mask-closable="false">
                    <div v-if="caseTypeList">
                        <custInfo ref="custInfo" :customTitle="customTitle" :Obj="caseType"/>
                    </div>
                </Modal>
            </div>
        </Card>
    </div>
</template>

<script>
    import approveHistory from "../common/approve-history/approve-history";
    import contractInfo from "../common/contract-info/contract-info";
    import insuranceBusiness from "../insurance/insuranceBusiness";
    import financeInfo from "../common/finance-info/finance-info";
    import custInsuranceInfo from "../common/cust-insurance/custInsuranceInfo";
    import custAnchorInfo from "../common/cust-anchor/custAnchorInfo";
    import custAssetInfo from "../common/cust-asset/custAssetInfo";
    import custInfo from "../common/case-type/case-type";
    import ContractCurrentUser from "_p/basic/pages/contract/common/current-user/contractCurrentUser";
    import {getByTypes} from "_p/basic/api/admin/datadic";
    import {getCase} from "_p/basic/api/contract/common/case-type/case-type";
    import {findByContractNo} from "_p/basic/api/contract/activated-case/index";
    import {businessSource, channelType, roleType} from "@/projects/basic/api/contract/channel-type/channel-type";
    import {checkFile} from "_p/basic/api/image/image-upload";
    import {
        getInsuranceData,
        save,
        saveProposalApplicationInfo,
        submit
    } from "_p/basic/api/contract/insurance/insuranceManage";
    import {verifyErrorToView, multiply, divided} from "_p/basic/assets/contract/js/utils";
    import {saveBasicInsurance,} from "_p/basic/api/contract/common/cust-insurance/cust-insurance";
    import {deepClone} from "@/libs/utils/ObjectClone";
    import PlaceCascade from "_p/basic/pages/contract/common/PlaceCascade";
    import {getLocation} from "_p/basic/api/contract/common/common";
    import {mapGetters} from "vuex";

    export default {
        components: {
            ContractCurrentUser,
            PlaceCascade,
            insuranceBusiness,
            custInsuranceInfo,
            custAnchorInfo,
            approveHistory,
            custAssetInfo,
            contractInfo,
            financeInfo,
            custInfo
        },
        data() {
            return {
                request: '',
                isSP: false,
                approveType: null,
                initLoadData: [],
                addressData: {},
                Obj: {},
                readOnly: null,
                contractNo: "",
                customTitle: null,
                insuranceBusiness: false,
                caseTypeList: false,
                editFlag: false,
                affiliatedType: true,
                dataDic: {},
                id: null,
                contractBusiness: ["insurance"],
                caseData: {
                    contractBusiness: [],
                    approvalOpinion: []
                },
                dicKeys: [
                    "trackingCompany"
                ],
                caseTitle: "自定义添加",
                submitLoading: false,
                caseType: null,
                processStatus: null,
                isApprove: null,
                isApproved: null,
                insuranceForm: {
                    consignee: '',
                    consigneeAdd: [],
                    trackingCompany: '',
                    trackingNo: '',
                    consigneePhone: '',
                    approvalOpinion: '',
                    reasonType: '',
                    emailNotification: '',
                },
                insuranceFormValidate: {
                    consignee: [
                        {required: true, message: "请输入收件人", trigger: "blur"}
                    ],
                    consigneeAdd: [
                        {required: true, type: 'array', message: "请选择收件地址", trigger: "change"}
                    ],
                    consigneeAddress: [
                        {required: true, message: "请输入收件地址", trigger: "blur"}
                    ],
                    approvalOpinion: [
                        {required: true, message: "请选择审批意见", trigger: "change"}
                    ],
                    consigneePhone: [
                        {required: true, message: "请输入收件人手机号码", trigger: "blur"}
                    ],
                    trackingCompany: [{required: true, message: "请选择快递公司", trigger: "change"}],
                    trackingNo: [{required: true, message: "请输入快递单号", trigger: "blur"}],
                },
                openPanel: ["1", "2", "3", "4", "5", "6", "7", "8"]
            };
        },
        created() {
            this.getParams();
        },
        computed: {
            ...mapGetters({userInfo: "userInfo", roleType: "roles"}),
            // 是否是合作商
            isFX: function () {
                return roleType(this.roleType);
            }
        },
        mounted() {
            if (!this.isSP) {
                this.initGetCase('contractBusiness');
                this.initGetCase('approvalOpinion');
                this.disabled = true;
                this.hidden = false;
            } else {
                this.disabled = false;
                this.hidden = true;
            }
            if (this.readOnly) {
                this.disabled = true;
            }
            this.initDataDic();
            if (this.Obj.editFlag) {
                this.getInsurance();
            }
            this.getInitData()
        },
        methods: {
            // 获取初始数据
            getParams() {
                const params = this.afs.getPageParams(this);
                const {processStatus} = params;
                this.editFlag = params.editFlag;
                this.readOnly = params.readOnly === "read";
                this.processStatus = params.processStatus;
                this.contractNo = params.contractNo;
                this.caseNo = params.caseNo;
                this.isSP = params.isSP;
                this.request = params.request;
                if (params.bizDataId === undefined) {
                    this.id = params.id;
                } else {
                    this.id = params.bizDataId;
                }
                this.isApprove =
                    !!processStatus &&
                    (processStatus === "repairedUnderReview" ||
                        processStatus === "underReview" ||
                        processStatus === "noSubmission" ||
                        processStatus === "submission");
                this.isApproved = !!processStatus && processStatus === "approved";
                this.Obj = {
                    type: 'insuranceClaim',
                    editFlag: params.editFlag,
                    contractNo: params.contractNo,
                    caseNo: params.caseNo,
                    roleType: this.isSP,
                    isFX: this.isFX,
                    processStatus: params.processStatus,
                    custName: params.custName,
                    id: params.id,
                    request: this.request,
                    currentAbsoluteOverdue: params.currentAbsoluteOverdue
                }
            },
            getInitData() {
                let param = {
                    level: "1",
                    upperCode: "1"
                };
                let request;
                if (!this.Obj.roleType) {
                    request = 'contractManage';
                } else {
                    request = 'apply';
                }
                getLocation(param, request).then(res => {
                    if (res.code == "0000") {
                        res.data.forEach(item => {
                            // 表明是否是父节点
                            if (item.isParent) {
                                item.loading = false;
                                item.children = [];
                            }
                        });
                    }
                    this.initLoadData.push(...res.data);
                });
            },
            cancel() {
                this.afs.closeTab(this);
            },
            initDataDic() {
                let self = this;
                getByTypes(this.dicKeys).then(res => {
                    if (res.code === "0000" && res.data) {
                        self.dataDic = res.data;
                    }
                });
            },
            getInsurance() {
                getInsuranceData(this.caseNo, this.request).then(res => {
                    if (res.code === "0000" && res.data) {
                        let d = res.data;
                        d.consigneeAdd = d.consigneeProvince && d.consigneeCity ? [d.consigneeProvince, d.consigneeCity] : []
                        this.insuranceForm = res.data;
                    }
                });
            },
            cancels(bool) {
                this.caseTypeList = bool;
            },
            initGetCase(type) {
                let self = this;
                getCase(type, this.Obj.type).then(res => {
                    if (res.code === "0000" && res.data) {
                        self.caseData[type] = res.data;
                    }
                });
            },
            affType(type) {
                this.affiliatedType = type;
            },
            caseTypeAdd(type) {
                if (type === 'contractBusiness') {
                    this.customTitle = "原因类型";
                } else if (type === 'approvalOpinion') {
                    this.customTitle = "审批意见";
                }
                this.insuranceBusiness = true;
                this.caseTypeList = true;
                this.caseType = {
                    caseType: type,
                    contractBusiness: this.Obj.type,
                }
            },
            formData() {
                let contractInfo = deepClone(this.$refs.contractInfo.formData);
                let insuranceForm = deepClone(this.insuranceForm);

                insuranceForm.applyNo = contractInfo.applyNo;
                insuranceForm.contractNo = contractInfo.contractNo;
                insuranceForm.custName = contractInfo.basicCustBaseInfo.custName;
                insuranceForm.currentAbsoluteOverdue = contractInfo.currentAbsoluteOverdue;
                insuranceForm.contractStatus = contractInfo.contractStatus;
                insuranceForm.channelFullName = contractInfo.channelFullName;
                // insuranceForm.channelType = contractInfo.channelType;
                insuranceForm.channelBelong = contractInfo.channelBelong;
                insuranceForm.carId = this.$refs.custAssetInfo.assetForm.id;
                insuranceForm.type = this.$refs.insuranceBusiness.insuranceBusinessForm.type;
                insuranceForm.certNo = contractInfo.basicCustBaseInfo.certNo;
                insuranceForm.businessSource = businessSource(this.isSP);
                if (Array.isArray(insuranceForm.consigneeAdd)) {
                    insuranceForm.consigneeProvince = insuranceForm.consigneeAdd[0];
                    insuranceForm.consigneeCity = insuranceForm.consigneeAdd[1];
                }

                if (this.isSP) {
                    insuranceForm.department = contractInfo.channelFullName;
                } else {
                    insuranceForm.department = this.userInfo.userRealName;
                }
                if (insuranceForm.type === "insuranceClaim") {
                    insuranceForm.claimForm = deepClone(this.$refs.insuranceBusiness.insuranceBusinessForm.claimForm);
                } else if (insuranceForm.type === "insuranceRenew") {
                    insuranceForm.json = deepClone(this.$refs.insuranceBusiness.insuranceBusinessForm.renewForm);
                } else if (insuranceForm.type === "insuranceChange") {
                    insuranceForm.changeForm = deepClone(this.$refs.insuranceBusiness.insuranceBusinessForm.changeForm);
                } else if (insuranceForm.type === "insuranceExit") {
                    insuranceForm.exitForm = deepClone(this.$refs.insuranceBusiness.insuranceBusinessForm.exitForm);
                }
                return insuranceForm;
            },
            submitInsurance() {
                let data = this.formData();
                let flag = true;
                let flag1 = true;

                if (flag1 && flag) {
                    save(data, this.request).then(res => {
                        if (res.code === "0000") {
                            let d = deepClone(res.data);

                            d.consigneeAdd = d.consigneeProvince && d.consigneeCity ? [d.consigneeProvince, d.consigneeCity] : [];

                            this.insuranceForm = d;
                            if (res.data.type === 'insuranceClaim') {
                                this.$refs.insuranceBusiness.insuranceBusinessForm.claimForm = d;
                            } else if (res.data.type === 'insuranceRenew') {
                                let json = JSON.parse(res.data.insureType);
                                this.$refs.insuranceBusiness.insuranceBusinessForm.renewForm = json;
                                this.$refs.insuranceBusiness.insuranceBusinessForm.renewForm.caseNo = d.caseNo;
                                this.$refs.insuranceBusiness.insuranceBusinessForm.renewForm.applyDate = d.applyDate;
                                this.$refs.insuranceBusiness.insuranceBusinessForm.renewForm.createBy = d.createBy;
                            } else if (res.data.type === 'insuranceChange') {
                                this.$refs.insuranceBusiness.insuranceBusinessForm.changeForm = d;
                            } else if (res.data.type === 'insuranceExit') {
                                this.$refs.insuranceBusiness.insuranceBusinessForm.exitForm = d;
                            }
                            this.$refs.insuranceBusiness.openUpload(
                                {
                                    editFlag: true,
                                    caseNo: d.caseNo,
                                }
                            );
                        }
                        this.$Message.success("保存成功");
                    });
                }
            },
            submit() {
                this.checkFile(this.$refs.insuranceBusiness.insuranceBusinessForm.type);
            },
            checkFile(type) {
                let params;
                if (type === 'insuranceClaim') {
                    params = {
                        busiNo: this.insuranceForm.caseNo,
                        busiType: "insuranceClaimImage",
                    };
                } else if (type === 'insuranceRenew') {
                    params = {
                        busiNo: this.insuranceForm.caseNo,
                        busiType: "insuranceRenewImage",
                    };
                } else if (type === 'insuranceChange') {
                    params = {
                        busiNo: this.insuranceForm.caseNo,
                        busiType: "insuranceChangeImage",
                    };
                } else if (type === 'insuranceExit') {
                    params = {
                        busiNo: this.insuranceForm.caseNo,
                        busiType: "insuranceExitImageImage",
                    };
                }
                checkFile(params).then(res => {
                    if (res.code === "0000") {
                        this.findByContractNo();
                    }
                })
            },
            findByContractNo() {
                let params = {
                    contractBusiness: this.contractBusiness,
                    contractNo: this.insuranceForm.contractNo,
                    handleBusiness: 'insurance'
                };
                if (this.insuranceForm.processStatus !== 'toBeRepaired') {
                    findByContractNo(params).then(res => {
                        if (res.code === "0000") {
                            if (res.msg === "success") {
                                this.fnSubmit();
                            }
                        }
                    });
                } else {
                    this.fnSubmit();
                }

            },
            fnSubmit() {
                let data = this.formData();
                let flag = true;
                this.$refs['insuranceForm'].validate(valid => {
                    flag = valid;
                    if (!valid)
                        verifyErrorToView(this.$refs['insuranceForm'].fields);
                });
                let flag1 = this.$refs['insuranceBusiness'].validateForm();
                if (flag1 && flag) {
                    this.insuranceForm.approvalOperating = 'suggestCheckF';
                    data.approvalOperating = 'suggestCheckF';
                    this.$Modal.confirm({
                        title: "确认提交",
                        content: "您确认要提交 ?",
                        onOk: () => {
                            this.submitQuery(data);
                        }
                    })
                } else {
                    this.$Message.error("必填项不能为空!");
                }
            },
            submitQuery(data) {
                submit(data, this.request).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success(res.msg);
                        this.cancel();
                    }
                });
            },
            through() {
                this.approveType = 'pass';
                let flag1 = this.$refs['insuranceBusiness'].validateForm();
                if (!flag1) return;
                this.$refs['insuranceForm'].validate(valid => {
                    if (!valid) {
                        verifyErrorToView(this.$refs['insuranceForm'].fields);
                    } else {
                        let data = this.formData();
                        this.insuranceForm.approvalOperating = 'suggestCheckF';
                        data.approvalOperating = 'suggestCheckF';
                        this.$refs.contractCurrentUser.formValidate("childUserForm", data, 'pass');
                    }
                });
            },
            goBack() {
                this.approveType = 'return';
                let data = this.formData();
                this.insuranceForm.approvalOperating = 'sendBack';
                data.approvalOperating = 'sendBack';
                this.$refs.contractCurrentUser.formValidate("childUserForm", data);
            },
            refuse() {
                this.approveType = 'reject';
                let data = this.formData();
                this.insuranceForm.approvalOperating = 'suggestRejectF';
                data.approvalOperating = 'suggestRejectF';
                this.$refs.contractCurrentUser.formValidate("childUserForm", data);
            },

            // 审核
            approve(data) {
                saveProposalApplicationInfo(data, this.request).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success(res.msg);
                        this.cancel();
                    }
                });
                if (this.insuranceForm.type === "insuranceRenew") {
                    this.insuranceForm.json.contractNo = this.insuranceForm.contractNo;
                    saveBasicInsurance(this.insuranceForm.json, channelType(this.$route.meta.params)).then(reset => {
                        if (res.code === "0000") {
                            this.$Message.success(res.msg);
                        }
                    });
                }
            },
            // contractCurrentUser 组件数据
            childUserForm(data) {
                if (!data) return;
                let t;
                switch (this.approveType) {
                    case "pass":
                        t = "审核通过";
                        break;
                    case "return":
                        t = "退件";
                        break;
                    case "reject":
                        t = "拒绝";
                        break;
                }
                this.$Modal.confirm({
                    title: `确认${t}？`,
                    onOk: () => {
                        this.approve(data)
                    }
                });
            },
            closeSpin() {

            },
        }
    };
</script>
<style lang="less">
    @import url("../../../styles/common/form.less");

    .contract-cancellation-detial-btns {
        padding-bottom: 16px;
    }

    .contract-cancellation-detial {
        .ivu-collapse-header {
            background-color: #f0faff;
        }
    }

    .insuranceInfoView {
        .ivu-date-picker,
        .ivu-select,
        .ivu-input,
        .ivu-input-number,
        .ivu-input-wrapper {
            min-width: 200px;
        }

        .place-cascade-box {
            .ivu-form-item {
                margin-right: 0;
            }

            .ivu-input-wrapper, .ivu-input {
                width: 100%;
                max-width: 100%;
                min-width: 250px;
            }
        }
    }
</style>
